package com.ztx.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ztx.annotation.AuthToken;
import com.ztx.pojo.Role;
import com.ztx.pojo.dto.RoleDto;
import com.ztx.pojo.dto.UserDto;
import com.ztx.service.PermissionService;
import com.ztx.service.RoleService;
import com.ztx.service.UserService;
import com.ztx.service.impl.UserServiceImpl;
import com.ztx.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AuthToken authTokenClass = handlerMethod.getBeanType().getAnnotation(AuthToken.class);
            AuthToken authTokenMethod = handlerMethod.getMethod().getAnnotation(AuthToken.class);

            // 如果方法或类上标记了注解
            if (authTokenMethod != null || authTokenClass != null) {
                // 从请求中获取Access Token
                String accessToken = request.getHeader("Authorization").substring(7);
                // 验证Access Token
                if (accessToken != null && redisTemplate.hasKey(accessToken)) {
                    // 验证权限 拿到用户id
                    Long userId = (Long) redisTemplate.opsForValue().get(accessToken);

                    // 查询userDto
                    UserDto userDto = userService.getByIdWithRoles(userId);
                    System.out.println(userDto);
                    // 角色列表
                    List<Role> roles = userDto.getRoles();
                    // 带有权限信息的角色列表
                    ArrayList<RoleDto> roleDtos = new ArrayList<>(roles.size());
                    for(Role role:roles){
                        RoleDto roleDto = roleService.getByIdWithPermissions(role.getRoleId());
                        roleDtos.add(roleDto);
                    }
                    // 根据role的method进行权限校验 后续可细分
                    return true;
                } else {
                    CommonResult result = CommonResult.error(401, "token无效");
                    String json = JSONObject.toJSONString(result);
                    response.setContentType("application/json;charset=utf8");
                    response.getWriter().write(json);
                    return false;
                }
            }
        }
        return true;
    }
}
